package com.ruoyi.industry.service.impl;

import java.util.*;

import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.uuid.IdUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.industry.domain.District;
import com.ruoyi.industry.domain.ProjectPark;
import com.ruoyi.industry.domain.SpaceIndustry;
import com.ruoyi.industry.mapper.*;
import com.ruoyi.industry.utils.EntrustUtil;
import com.ruoyi.system.api.RemoteFileService;
import com.ruoyi.system.api.domain.PathVo;
import com.ruoyi.system.api.domain.SysUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.industry.domain.ProjectBuilding;
import com.ruoyi.industry.service.IProjectBuildingService;

import javax.servlet.http.HttpServletResponse;

/**
 * 项目-楼宇办公/商用Service业务层处理
 *
 * @author MagicCube
 * @date 2023-05-08
 */
@Service
public class ProjectBuildingServiceImpl implements IProjectBuildingService
{
    private static final Logger log = LoggerFactory.getLogger(ProjectAuctionServiceImpl.class);

    @Autowired
    private ProjectBuildingMapper projectBuildingMapper;

    @Autowired
    private SpaceIndustryMapper spaceIndustryMapper;

    @Autowired
    private DistrictMapper districtMapper;

    @Autowired
    private SpaceCollectMapper spaceCollectMapper;

    @Autowired
    private ProjectParkMapper projectParkMapper;

    @Autowired
    private RemoteFileService remoteFileService;
    /**
     * 查询项目-楼宇办公/商用
     *
     * @param id 项目-楼宇办公/商用主键
     * @return 项目-楼宇办公/商用
     */
    @Override
    public ProjectBuilding selectProjectBuildingById(Long id)
    {
        return projectBuildingMapper.selectProjectBuildingById(id);
    }

    /**
     * 查询项目-楼宇办公/商用列表
     *
     * @param projectBuilding 项目-楼宇办公/商用
     * @return 项目-楼宇办公/商用
     */
    @Override
    public List<ProjectBuilding> selectProjectBuildingList(ProjectBuilding projectBuilding)
    {
        return projectBuildingMapper.selectProjectBuildingList(projectBuilding);
    }
    @Override
    public List<ProjectBuilding> selectProjectBuildingListz(ProjectBuilding projectBuilding)
    {
//        List<Long> districtIds = new ArrayList<Long>();
//        //城市
//        if (projectBuilding.getCityId()!=null){
//            districtIds.add(projectBuilding.getCityId());
//            projectBuilding.setCityIds(districtIds);
//        }else if (projectBuilding.getCityId()==null && projectBuilding.getProvinceId() != null){
//            //查询省份下的城市
//            districtIds.addAll(districtMapper.selectDistrictIdList(projectBuilding.getProvinceId()));
//            districtIds.add(projectBuilding.getProvinceId());
//            projectBuilding.setCityIds(districtIds);
//        }
        if (projectBuilding.getBuildSellPrice()!=null){
            String[] split = projectBuilding.getBuildSellPrice().split("~");
            projectBuilding.setBuildSellPriceLow(Long.parseLong(split[0]));
            if (!split[1].equals("N")) {
                projectBuilding.setBuildSellPriceHigh(Long.parseLong(split[1]));
            }
        }
        //租赁价格
        if(projectBuilding.getBuildLeasePrice()!=null){
            String[] split = projectBuilding.getBuildLeasePrice().split("~");
            projectBuilding.setBuildLeasePriceLow(Long.parseLong(split[0]));
            if (!split[1].equals("N")) {
                projectBuilding.setBuildLeasePriceHigh(Long.parseLong(split[1]));
            }
        }
        //应急系统
//        if (projectBuilding.getBuildEmergency() != null && projectBuilding.getBuildEmergency().equals("H")) {
//            projectBuilding.setBuildEmergency("有");
//        } else if (projectBuilding.getBuildEmergency() != null && projectBuilding.getBuildEmergency().equals("N")) {
//            projectBuilding.setBuildEmergency("无");
//        }
//        if (!SecurityUtils.getLoginUser().getRoles().contains("admin")){
//            projectBuilding.setSupplyUserId(SecurityUtils.getUserId());
//        }
        List<ProjectBuilding> projectBuildings = projectBuildingMapper.selectProjectBuildingListz(projectBuilding);
//        for (ProjectBuilding building : projectBuildings) {
//            SysUser sysUser = spaceIndustryMapper.selectSysUserById(building.getServicePhone());
//            if (sysUser!=null) {
//                if (sysUser.getNickName()!=null&&!sysUser.getNickName().equals("")) {
//                    building.setContactName(sysUser.getNickName());
//                }else {
//                    building.setContactName(sysUser.getUserName());
//                }
//                building.setContactPhone(sysUser.getPhonenumber());
//            }
//        }
        return projectBuildings;
    }

    /**
     * 新增项目-楼宇办公/商用
     *
     * @param projectBuilding 项目-楼宇办公/商用
     * @return 结果
     */
    @Override
    public int insertProjectBuilding(ProjectBuilding projectBuilding)
    {
        projectBuilding.setSupplyUserId(SecurityUtils.getUserId());
        if (projectBuilding.getApprovalState() == null) {
//            if (SecurityUtils.getLoginUser().getRoles().contains("admin")) {
//                projectBuilding.setApprovalState(1L);
//            } else {
                projectBuilding.setApprovalState(0L);
//            }
        }
        projectBuilding.setCreateTime(DateUtils.getNowDate());
        projectBuilding.setSerialNumber(IdUtils.fastSimpleUUID());
        SpaceIndustry spaceIndustry = new SpaceIndustry();
        extracted(projectBuilding, spaceIndustry);
        spaceIndustry.setCreateBy(SecurityUtils.getUsername());
        spaceIndustry.setCreateTime(projectBuilding.getCreateTime());
        spaceIndustry.setSpaceId(projectBuilding.getSerialNumber());
        spaceIndustry.setSupplyUserId(projectBuilding.getSupplyUserId());
        spaceIndustryMapper.insertSpaceIndustry(spaceIndustry);
        return projectBuildingMapper.insertProjectBuilding(projectBuilding) ;
    }

    private static void extracted(ProjectBuilding projectBuilding, SpaceIndustry spaceIndustry) {
        spaceIndustry.setBuildType(projectBuilding.getBuildType());
        spaceIndustry.setReleaseType(projectBuilding.getReleaseType());
        spaceIndustry.setApprovalState(projectBuilding.getApprovalState());
        spaceIndustry.setProvinceId(projectBuilding.getProvinceId());//省份
        spaceIndustry.setCityId(projectBuilding.getCityId());//城市
//        spaceIndustry.setAreaId();//区域
        spaceIndustry.setSupplyType(projectBuilding.getSupplyType());//服务类型
        spaceIndustry.setParkId(String.valueOf(projectBuilding.getParkId()));
        spaceIndustry.setHeating(projectBuilding.getBuildHeating());//供暖
        spaceIndustry.setRefrig(projectBuilding.getBuildRefrig());//制冷
        spaceIndustry.setPower(projectBuilding.getBuildPower());//电力
        spaceIndustry.setGas(projectBuilding.getBuildGas());//燃气
        spaceIndustry.setLeasePrice(projectBuilding.getBuildLeasePrice());//出售价格
        spaceIndustry.setSellPrice(projectBuilding.getBuildSellPrice());//租赁价格
        spaceIndustry.setCoverResource(projectBuilding.getCoverResource());//封面资源
        spaceIndustry.setSpaceName(projectBuilding.getBuildName());//园区名称
        spaceIndustry.setSpaceAllSize(projectBuilding.getBuildAllSize());//空间总面积
        spaceIndustry.setTop(projectBuilding.getTop());//置顶
        spaceIndustry.setRecomState(projectBuilding.getRecomState());

//        spaceIndustry.setCityId(projectBuilding.getCityId());
//        spaceIndustry.setPageView(projectBuilding.getPageView());
//        spaceIndustry.setCollectState(projectBuilding.getCollectState());
//        spaceIndustry.setRecState(projectBuilding.getRecState());
//        spaceIndustry.setReserveState(projectBuilding.getReserveState());
//        spaceIndustry.setVrResource(projectBuilding.getVrResource());
//        spaceIndustry.setImgResource(projectBuilding.getImgResource());
//        spaceIndustry.setCoverResource(projectBuilding.getCoverResource());
//        spaceIndustry.setContactName(projectBuilding.getContactName());
//        spaceIndustry.setServicePhone(projectBuilding.getServicePhone());
//        spaceIndustry.setContactPhone(projectBuilding.getContactPhone());
//        spaceIndustry.setSupplyUserId(projectBuilding.getSupplyUserId());
//        spaceIndustry.setApprovalNote(projectBuilding.getApprovalNote());
//        spaceIndustry.setRemark(projectBuilding.getNote());
//        spaceIndustry.setSort(projectBuilding.getSort());
//        spaceIndustry.setVrcover(projectBuilding.getVrcover());
//        spaceIndustry.setTop(projectBuilding.getTop());
    }

    /**
     * 修改项目-楼宇办公/商用
     *
     * @param projectBuilding 项目-楼宇办公/商用
     * @return 结果
     */
    @Override
    public int updateProjectBuilding(ProjectBuilding projectBuilding)
    {
        if (projectBuilding.getApprovalState() == null) {
            projectBuilding.setApprovalState(0L);
        }
        //根据id查询
        projectBuilding.setUpdateTime(DateUtils.getNowDate());
        SpaceIndustry spaceIndustry = new SpaceIndustry();
        extracted(projectBuilding,spaceIndustry);
        spaceIndustry.setSpaceId(String.valueOf(projectBuilding.getId()));
        spaceIndustry.setUpdateBy(SecurityUtils.getUsername());
        spaceIndustry.setUpdateTime(projectBuilding.getUpdateTime());
        spaceIndustryMapper.updateSpaceIndustryByBuildId(spaceIndustry);
        return projectBuildingMapper.updateProjectBuilding(projectBuilding);
    }

    /**
     * 批量删除项目-楼宇办公/商用
     *
     * @param ids 需要删除的项目-楼宇办公/商用主键
     * @return 结果
     */
    @Override
    public int deleteProjectBuildingByIds(Long[] ids)
    {
        List<String> pathList = new ArrayList<>();
        for (ProjectBuilding projectBuilding : projectBuildingMapper.selectProjectBuildingByIds(ids)) {
            spaceIndustryMapper.deleteSpaceRecomById("楼宇", projectBuilding.getId());
            SpaceIndustryServiceImpl.deleteFile(
                    pathList,
                    projectBuilding.getVrResource(),
                    projectBuilding.getImgResource(),
                    projectBuilding.getCoverResource(),
                    projectBuilding.getVrcover(),
                    projectBuilding.getQrCode()
            );
        }
        spaceIndustryMapper.deleteSpaceIndustryByProjectBuildingIds(ids);
        remoteFileService.delete(new PathVo(pathList), SecurityConstants.INNER);
        return projectBuildingMapper.deleteProjectBuildingByIds(ids);
    }

    /**
     * 删除项目-楼宇办公/商用信息
     *
     * @param id 项目-楼宇办公/商用主键
     * @return 结果
     */
    @Override
    public int deleteProjectBuildingById(Long id)
    {
        ProjectBuilding projectBuilding = projectBuildingMapper.selectProjectBuildingById(id);
        List<String> pathList = new ArrayList<>();
        SpaceIndustryServiceImpl.deleteFile(
                pathList,
                projectBuilding.getVrResource(),
                projectBuilding.getImgResource(),
                projectBuilding.getCoverResource(),
                projectBuilding.getVrcover(),
                projectBuilding.getQrCode()
        );
        remoteFileService.delete(new PathVo(pathList), SecurityConstants.INNER);
        spaceIndustryMapper.deleteSpaceRecomById("楼宇",projectBuilding.getId());
        spaceIndustryMapper.deleteSpaceIndustryByProjectBuildingId(id);
        return projectBuildingMapper.deleteProjectBuildingById(id);
    }

    @Override
    public Map<String, Object> selectProjectBuildingByNumber(String spaceId, boolean show) {
        ProjectBuilding projectBuilding = projectBuildingMapper.selectProjectBuildingByNumber(spaceId);
        if (SecurityUtils.getUserId() != null&&SecurityUtils.getUserId()!=0) {
            if (show) {
                spaceIndustryMapper.updatePageViews(spaceId);
                projectBuildingMapper.updatePageViews(spaceId);
            }
            List<String> list = spaceCollectMapper.selectSpaceCollectByUserId(SecurityUtils.getUserId(), spaceId);
            if (list != null && list.size() != 0) {
                projectBuilding.setCollectState(1L);
            } else {
                projectBuilding.setCollectState(0L);
            }
        }else {
            projectBuilding.setCollectState(0L);
        }
        if (projectBuilding.getProvinceId()!=null){
            District district = districtMapper.selectDistrictById(projectBuilding.getProvinceId());
            projectBuilding.setCityName(district.getName());
        }
        if (projectBuilding.getCityId()!=null){
            District district = districtMapper.selectDistrictById(projectBuilding.getCityId());
            projectBuilding.setCityName(projectBuilding.getCityName()+district.getName());
        }
        SysUser sysUser = spaceIndustryMapper.selectSysUserById(projectBuilding.getServicePhone());
        if (sysUser!=null){
            projectBuilding.setContactName(sysUser.getNickName());
            projectBuilding.setContactPhone(sysUser.getPhonenumber());
            projectBuilding.setQrCode(sysUser.getCodePic());
        }
//        if (projectBuilding.getAreaId()!=null){
//            District district = districtMapper.selectDistrictById(projectBuilding.getAreaId());
//            projectBuilding.setCityName(projectBuilding.getCityName()+district.getName());
//        }
        Map<String, Object> map = new HashMap<>();
        SpaceIndustry spaceIndustry = spaceIndustryMapper.selectSpaceIndustryBySpaceId(spaceId);
        if (spaceIndustry!=null){
            projectBuilding.setPageView(Long.valueOf(spaceIndustry.getPageViews()));
        }
        map.put("space",projectBuilding);
        if (projectBuilding.getParkId()!=null) {
            ProjectPark projectPark = projectParkMapper.selectProjectParkById(projectBuilding.getParkId());
            map.put("park",projectPark);
        }else {
            map.put("park",null);
        }
        return map;
    }

    @Override
    public int deleteProjectBuildingBySerialNumber(String spaceId) {
        ProjectBuilding projectBuilding = projectBuildingMapper.selectProjectBuildingByNumber(spaceId);
        List<String> pathList = new ArrayList<>();
        SpaceIndustryServiceImpl.deleteFile(
                pathList,
                projectBuilding.getVrResource(),
                projectBuilding.getImgResource(),
                projectBuilding.getCoverResource(),
                projectBuilding.getVrcover(),
                projectBuilding.getQrCode()
        );
        remoteFileService.delete(new PathVo(pathList), SecurityConstants.INNER);
        spaceIndustryMapper.deleteSpaceRecomById("楼宇",projectBuilding.getId());
        spaceIndustryMapper.deleteSpaceIndustryByProjectBuildingId(projectBuilding.getId());
        return projectBuildingMapper.deleteProjectBuildingById(projectBuilding.getId());
//        spaceIndustryMapper.deleteSpaceIndustryBySerialNumber(spaceId);
//        return projectBuildingMapper.deleteProjectBuildingBySerialNumber(spaceId);
    }

    private static final List<Long> STATE = Arrays.asList(0L,1L,2L,3L);

    @Override
    public String importUser(List<ProjectBuilding> projectBuildings, boolean updateSupport, String operName, Integer buildType) {

        if (StringUtils.isNull(projectBuildings) || projectBuildings.size() ==0){
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        Long count = 0L;
        for (ProjectBuilding projectBuilding : projectBuildings) {
            if (projectBuildings.indexOf(projectBuilding)==0&&projectBuilding.getBuildName().equals("楼宇名称")){
                continue;
            }
            count++;
            projectBuilding.setBuildType(buildType);
            try {
                if (projectBuilding.getApprovalState()==null||STATE.contains(projectBuilding.getApprovalState())){
                    projectBuilding.setApprovalState(0L);
                }
                if (projectBuilding.getSupplyUserId()==null){
                    projectBuilding.setSupplyUserId(SecurityUtils.getUserId());
                }
                if (projectBuilding.getBuildName()==null||projectBuilding.getBuildName().equals("")){
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、第 " + count + "条数据 缺少楼宇名称");
                    break;
                }
                projectBuilding.setCreateBy(SecurityUtils.getUsername());
                projectBuilding.setCreateTime(DateUtils.getNowDate());
                projectBuildingMapper.insertProjectBuilding(projectBuilding);
                successNum++;
                successMsg.append("<br/>" + successNum + "、楼宇 " + projectBuilding.getBuildName() + " 导入成功");
            }catch (Exception e){
                failureNum++;
                String msg = "<br/>" + failureNum + "、楼宇 " + projectBuilding.getBuildName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public void exportEntrust(HttpServletResponse response, Long id) {
        ProjectBuilding modal = projectBuildingMapper.selectProjectBuildingById(id);
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("需求类型：" + modal.getSupplyType() + "<w:br/>");
        stringBuffer.append("园区类型：" + modal.getParkType() + "<w:br/>");
        stringBuffer.append("区域位置：" + modal.getParkAreaAddress() + "<w:br/>");
        stringBuffer.append("商圈：" + modal.getParkDistrict() + "<w:br/>");
        stringBuffer.append("求租价格：" + modal.getBuildLeasePrice() + "<w:br/>");
        stringBuffer.append("求购价格：" + modal.getBuildSellPrice() + "<w:br/>");
        stringBuffer.append("需求面积：" + modal.getBuildNeedSize() + "<w:br/>");
        stringBuffer.append("首层承重：" + modal.getBuildFirstLoad() + "<w:br/>");
        stringBuffer.append("标准层承重：" + modal.getBuildLoad() + "<w:br/>");
        stringBuffer.append("层高要求：" + modal.getBuildPlaceFloor() + "<w:br/>");
        stringBuffer.append("供暖：" + modal.getBuildHeating() + "<w:br/>");
        stringBuffer.append("制冷：" + modal.getBuildRefrig() + "<w:br/>");
        stringBuffer.append("新风系统：" + modal.getBuildNather() + "<w:br/>");
        stringBuffer.append("电量：" + modal.getBuildPower() + "<w:br/>");
        stringBuffer.append("燃气：" + modal.getBuildGas() + "<w:br/>");
        stringBuffer.append("水：" + modal.getBuildWater() + "<w:br/>");
        stringBuffer.append("装修程度：" + modal.getBuildRenova() + "<w:br/>");
        stringBuffer.append("客梯：" + modal.getBuildElevatorPeople() + "<w:br/>");
        stringBuffer.append("客梯负载：" + modal.getBuildElevatorPeopleLoad() + "<w:br/>");
        stringBuffer.append("货梯：" + modal.getBuildElevatorCargo() + "<w:br/>");
        stringBuffer.append("货梯负载：" + modal.getBuildElevatorCargoLoad() + "<w:br/>");
        stringBuffer.append("消防设施：" + modal.getBuildFireControl() + "<w:br/>");
        stringBuffer.append("应急系统：" + modal.getBuildEmergency() + "<w:br/>");
        stringBuffer.append("车位：" + modal.getParkCarlot() + "<w:br/>");
        stringBuffer.append("联系人：" + modal.getContactName() + "<w:br/>");
        stringBuffer.append("联系人方式：" + modal.getContactPhone() + "<w:br/>");
        new EntrustUtil().exportWord(stringBuffer,response);
    }
}
